package org.gruposp2p.proyectokarma.controller

import org.gruposp2p.proyectokarma.command.*;
import org.gruposp2p.proyectokarma.domain.*;

class ImageController {

    def index = {
        //redirect(action:upload)
        render(view:"upload")
    }

   def upload = { UploadImageCommand command ->
       //if(command.hasErrors()) {redirect(action:}
	   def maxFileSize = grailsApplication.config.image.maxFileSize
	   if (command.contents.size > maxFileSize) {
		  response.status = 400  //Bad Request
		  render message(code: 'proyectokarma.image.fileTooBig', args:[maxFileSize])
		  return
	  }
	  def image = new Image(command.contents.getOriginalFilename(),
          command.contents.getContentType(), command.contents.bytes);
	  image.save(flush: true)
	  log.debug "Image ${command.contents.getOriginalFilename()} loaded"
   }

   def get = {
        def image
        if (params.int("imageId")) image = Image.findById(params.imageId)
        if (!image) {
            response.status = 404
            render message(code: 'proyectokarma.image.imageNotFound', args:[params.imageId])
            return;
        }
        //def file = new File(params.fileDir)
        response.setContentType(image.getContentType())
        response.setHeader("Content-disposition", "filename=${image.getName()}")
        response.outputStream << image.getBytes() // Performing a binary stream copy
		response.outputStream.flush()
   }

   def delete = {
	   if (params.id) {
		   def image = Image.get(params.id)
		   if (image) image.delete()
		   else {
			   response.status = 404;
			   render message(code: 'proyectokarma.image.deleteNotFound', args:[params.id])
			   return
		   }
		   response.status = 200;
		   render message(code: 'proyectokarma.image.deleteOK', args:[params.id])
		   return
	   } else {
		   response.status = 400  //Bad Request
		   render message(code: 'proyectokarma.image.deleteBadRequest')
		   return;
	   }
   }
   
}